#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
from rbac import models
from rbac.forms.Base import BootStrapModelForm
from django.contrib.auth.hashers import make_password, check_password


class UserModelForm(BootStrapModelForm):
    passwd = forms.CharField(label='密码', widget=widgets.PasswordInput)
    re_passwd = forms.CharField(label='确认密码', widget=widgets.PasswordInput)

    def __init__(self, *args, **kwargs):
        super(UserModelForm, self).__init__(*args, **kwargs)
        self.fields['phone'].required = False

    class Meta:
        model = models.User
        fields = ['username', 'email', 'phone', 'fullname', 'passwd', 're_passwd','depart']

    def clean_re_passwd(self):
        passwd = self.cleaned_data.get('passwd', None)
        re_passwd = self.cleaned_data.get('re_passwd', None)

        if passwd != re_passwd and re_passwd:
            raise ValidationError('两次密码不一致!')

        re_passwd = make_password(re_passwd)
        self.cleaned_data['passwd'] = re_passwd
        return re_passwd

    def clean(self):
        if self.cleaned_data.get('re_passwd', None):
            re_passwd = self.cleaned_data['re_passwd']
            self.cleaned_data['passwd'] = re_passwd
            return self.cleaned_data


class UpdateUserModelForm(forms.ModelForm):
    class Meta:
        model = models.User
        fields = ['fullname', 'email', 'phone', 'roles','depart']
        widgets = {
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
            'fullname': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'roles': forms.SelectMultiple(attrs={'class': 'form-control select2_multi'})
        }


class ResetPasswordUserModelForm(BootStrapModelForm):
    passwd = forms.CharField(label='密码',widget=widgets.PasswordInput)
    re_passwd = forms.CharField(label='确认密码', widget=widgets.PasswordInput)

    class Meta:
        model = models.User
        fields = ['passwd', 're_passwd']

    def clean_re_passwd(self):
        """
        检测密码是否一致
        :return:
        """
        passwd = self.cleaned_data.get('passwd', None)
        re_passwd = self.cleaned_data['re_passwd']
        if passwd != re_passwd:
            raise ValidationError('两次密码输入不一致')
        self.cleaned_data['passwd'] = make_password(re_passwd)
        return make_password(re_passwd)
